package com.weihao.sd.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weihao.sd.wx.msg.req.TextMsg;
import com.weihao.sd.wx.msg.resp.Article;
import com.weihao.sd.wx.msg.resp.NewsMsg;

public class WxClientUtils {

	private static Logger logger = LoggerFactory.getLogger(WxClientUtils.class);

	private static HttpClient httpClient = new DefaultHttpClient();

	private static long startTime = 0L;

	private static long endTime = 0L;

	public final static String ERROR_CODE = "errcode";
	public final static String ERROR_MSG = "errmsg";

	public static JSONObject postWx(String url, String json)
			throws JSONException {

		logger.info("httpclient postwx开始。");

		HttpPost method = new HttpPost(url);

		StringEntity entity = new StringEntity(json, "utf-8");// 解决中文乱码问题
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		method.setEntity(entity);

		JSONObject resJson = null;
		String errorCode = "0";
		String errorMsg = "";
		try {
			startTime = System.currentTimeMillis();

			HttpResponse result = httpClient.execute(method);

			endTime = System.currentTimeMillis();
			int statusCode = result.getStatusLine().getStatusCode();

			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			if (statusCode == HttpStatus.SC_OK) {
				String resData = EntityUtils.toString(result.getEntity(),
						"UTF-8");
				resJson = new JSONObject(resData);
				return resJson;
			}

		} catch (ClientProtocolException e) {
			errorMsg = "接口调用失败:" + url;
			logger.error("接口调用失败", e);
			// e.printStackTrace();
		} catch (ParseException e) {
			errorMsg = "结果转换失败";
			logger.error("结果转换失败", e);
			// e.printStackTrace();
		} catch (IOException e) {
			errorMsg = "IO异常，网络传输异常";
			logger.error("IO异常,网络传输异常", e);
			e.printStackTrace();
		} catch (JSONException e) {
			errorMsg = "JSON转换失败";
			logger.error("JSON转换失败", e);
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		resJson.put(ERROR_CODE, errorCode);
		resJson.put(ERROR_MSG, errorMsg);
		return resJson;
	}

	public static JSONObject getWx(String url) throws ClientProtocolException,
			IOException, JSONException {
		logger.info("httpclient getwx开始。");
		HttpGet method = new HttpGet(url);

		JSONObject resJson = null;
		String errorCode = "0";
		String errorMsg = "";
		try {
			startTime = System.currentTimeMillis();

			HttpResponse result = httpClient.execute(method);

			endTime = System.currentTimeMillis();
			int statusCode = result.getStatusLine().getStatusCode();

			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			if (statusCode == HttpStatus.SC_OK) {
				String resData = EntityUtils.toString(result.getEntity(),
						"UTF-8");
				resJson = new JSONObject(resData);
				return resJson;
			}

		} catch (ClientProtocolException e) {
			errorMsg = "接口调用失败:" + url;
			logger.error("接口调用失败", e);
			// e.printStackTrace();
		} catch (ParseException e) {
			errorMsg = "结果转换失败";
			logger.error("结果转换失败", e);
			// e.printStackTrace();
		} catch (IOException e) {
			errorMsg = "IO异常，网络传输异常";
			logger.error("IO异常,网络传输异常", e);
			e.printStackTrace();
		} catch (JSONException e) {
			errorMsg = "JSON转换失败";
			logger.error("JSON转换失败", e);
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		resJson.put(ERROR_CODE, errorCode);
		resJson.put(ERROR_MSG, errorMsg);
		return resJson;

	}

	public static String processRequest(HttpServletRequest request) {
		
		logger.warn("进入处理请求。");
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");

			// 回复文本消息
			TextMsg textMsg = new TextMsg();
			textMsg.setToUserName(fromUserName);
			textMsg.setFromUserName(toUserName);
			textMsg.setCreateTime(new Date().getTime());
			textMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMsg.setFuncFlag(0);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				logger.warn("您发送的是文本消息！");
				respContent = "您发送的是文本消息！";
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				logger.warn("您发送的是图片消息！");
				respContent = "您发送的是图片消息！";
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				logger.warn("您发送的是地理位置消息！");
				respContent = "您发送的是地理位置消息！";
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				logger.warn("您发送的是链接消息！");
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				logger.warn("您发送的是音频消息！");
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				logger.warn("您发送的是事件，类型为："+eventType+" ！");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "谢谢您的关注！";
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// TODO 自定义菜单权没有开放，暂不处理该类消息
					String eventKey = requestMap.get("EventKey");
					logger.warn("您点击的事件，key为："+eventKey+" ！");

					if (eventKey.equals("cj_txt")) {
						logger.warn("德懿创俱菜单！");
						StringBuffer buffer = new StringBuffer();
						buffer.append(
								"【徳懿创俱】---徳懿创投俱乐部，是由广州德懿信息技术有限公司建立的，以创业和投资为核心的一个信息交流平台！本创投俱乐部聚集全国各地技术、营销、创业精英和投资商，汇聚各类非常有潜力的投资项目，欢迎广大对创业或投资感兴趣的朋友加入本俱乐部！开放对象：各行业创业者、技术和营销精英、各类投资商！")
								.append("\n");
						buffer.append("旗下创业项目：").append("\n\n");
						buffer.append("1、服装O2O微电商项目（厂家直供）：8月份上线").append("\n");
						buffer.append("2、电器O2O微电商项目（厂家直供）：7月份已上线").append("\n");
						buffer.append("3、进口免税品O2O微电商项目（海关免税仓直供）：8月份上线").append(
								"\n");
						buffer.append("4、无人机O2O微电商项目（厂家直供）：筹备中").append("\n");
						buffer.append("5、3D打印O2O微电商项目（厂家直供）：筹备中")
								.append("\n\n");
						buffer.append("商务合作：董经理 13602832685").append("\n");
						buffer.append("微信号：404908046").append("\n");
						buffer.append(
								"备注：【徳懿创俱】微信公众平台及时公布最新创业项目，请各位朋友留意本公司公众号的最新消息！")
								.append("\n");
						respContent = buffer.toString();
						NewsMsg newsMsg = new NewsMsg();
						newsMsg.setArticleCount(1);
						List<Article> articles = new ArrayList<Article>();
						Article a = new Article();
						a.setDescription(respContent);
						a.setTitle("徳懿创俱");
						articles.add(a);
						newsMsg.setArticles(articles);
						newsMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
						newsMsg.setFromUserName(toUserName);
						newsMsg.setToUserName(fromUserName);
						respMessage = MessageUtil.newsMessageToXml(newsMsg);
						return respMessage;

					}
				}
			}
			logger.warn("类型判断完毕，准备回复消息。");
			textMsg.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMsg);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
//			e.printStackTrace();
		}

		return respMessage;
	}

	public static AccessToken getAccessToken(String appid, String appsecret){
		
		String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
				+ appid + "&secret=" + appsecret;
		
		AccessToken accessToken = null;
		JSONObject wx;
		try {
			wx = getWx(tokenUrl);
			if (!wx.has(ERROR_CODE)) {
				accessToken = new AccessToken();
				accessToken.setToken(wx.getString("access_token"));
				accessToken.setExpiresIn(wx.getInt("expires_in"));
				logger.warn("获取accessToken成功!");
			}else{
				logger.error(wx.getString(ERROR_MSG));
			}
		} catch (JSONException e) {
			logger.error("JSON转换出错!",e);
		}catch (Exception e) {
			logger.error("其他异常",e);
		}
		
		return accessToken;
	}
	

}
